package com.study.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/*********************************************************
 * @Author ONE_LLX
 * @Description //TODO 
 * @Date 18:00 2019/11/12
 * @Class HelloController
 * @Version v1.0
 *********************************************************/
@CrossOrigin(origins = "*", maxAge = 3600, methods = {RequestMethod.POST, RequestMethod.GET})
@RestController
@RequestMapping("/hello")
public class HelloController {

    @RequestMapping(value = "/find/list", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public String findList(HttpSession session,
                           HttpServletResponse response) {
//        System.out.println(1/0);
        Subject subject = SecurityUtils.getSubject();
        System.out.println(subject.getPrincipal().toString());
        session.setAttribute("hello","123");
        Cookie cookie=new Cookie("username","23");
        response.addCookie(cookie);
        return session.getId();
    }


    @RequestMapping(value = "/get", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public String find(HttpSession session, HttpServletResponse response,
                       HttpServletRequest request) {
//        System.out.println(1/0);
        Object hello = session.getAttribute("hello");
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie:
             cookies) {
            System.out.println(cookie.getName());
            System.out.println(cookie.getValue());
        }
        System.out.println(hello.toString());
        return session.getId();
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public String find(HttpSession session, HttpServletResponse response,
                       HttpServletRequest request,
                       @RequestParam String account,@RequestParam String passwd) {
//        System.out.println(1/0);
        UsernamePasswordToken token= null;
        try {
            token =new UsernamePasswordToken(account,passwd);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            return "true";
        }catch (AuthenticationException e){
            token.clear();
            e.printStackTrace();
            return "false";
        }

    }
}
